<!-- 选择详情地址
      高德地图
      选择添加地址 -->

<template>
  <el-dialog title="搜索查看地址" class="showAddress" :close-on-click-modal="false" :modal-append-to-body='false' v-dialogDrag
             :visible.sync="mapVisible">
    <div id="container" style="height: 100%;width: 100%;z-index:999"></div>
    <!--  搜索部分     -->

    <section class="dialogSearch dialogSearchMap">
      <div v-if="showCity" style="margin-right:30px;display: flex"
      >
        <span class="p1">当前城市：</span>
        <search-city ref="searchCity" @upMap="upMap"></search-city>
      </div>
      <!--  搜索部分     -->
      <el-input
          placeholder="请输入地址"
          @input="searchKeyword" v-model="inputSearchVal"
          suffix-icon="el-icon-search"
          clearable
      >
      </el-input>

    </section>
    <section class="searchBox" v-if="inputSearchVal!==''">
      <section style="height:100%; overflow-y: auto">
        <p class="s_p1">共搜索到 <span style="color:#1890FF ">{{ resultCount }}</span>个地址</p>
        <div class="s_item" v-for="(item,index) in poiArr" @click="chooseCenter(item)">
          <div class="s_t_left">
            <i class="icon"></i>
          </div>
          <div class="s_t_right">
            <p class="s_p2">{{ item.name }}</p>
            <p class="s_p3">{{ item.address }}</p>
          </div>
        </div>

      </section>
    </section>

  </el-dialog>
</template>

<script>
import AMap from 'AMap'
import searchCity from './searchCity'

export default {
  name: 'Gmap',
  components: {
    searchCity
  },
  props: {
    showCity: {   // 是否显示三级联动
      type: Boolean,
      default: true
    },
    initVal: {
      type: String
    }
  },
  data () {
    return {
      /* ======= 地图相关数据 ============== */
      province: '',               // 省
      city: '', // 市
      districtVal: '', // 县区
      provinceList: [],                              // 省list
      cityList: [],                                  // 城市list
      districtList: [],                              // 县区list
      cityCode: '',                                  // 选择所在地的城市名字code
      resultCount: 0,                                // 地图结果条数
      poiArr: [],                                    // 搜索出来的位置
      autoCompleteComponent: undefined,              // 组件
      placeSearchComponent: undefined,               // 组件
      inputSearchVal: '',                            // 搜索的位置名称
      mapVisible: false,                             // 控制地图的展示和隐藏
      otherAddress: '',                               // 其他地址
      addressComponent: [],
      addressComponentObj: {}

    }
  },
  methods: {
    upMap (val, level, otherAddress) {
      this.otherAddress = otherAddress
      this.inputSearchVal = ''
      this.cityCode = val.adcode
      this.mapSearchInit()
      this.map.setCenter(val.center)
      let district = new AMap.DistrictSearch()
      district.search(val.adcode, (status, result) => {
        if (status === 'complete') {
          if (level === 'province') {
            this.cityList = result.districtList[0].districtList
          }
          if (level === 'city') {
            this.districtList = result.districtList[0].districtList
          }
        }
      })
    },
    /* ================  地图相关 ==================   */
    // 选择搜索定位对应的地方
    chooseCenter (item) {
      this.map.setZoomAndCenter(15, item.location)
      this.inputSearchVal = ''
      // 选择后对地图标点
      this.marker(item.location)
    },
    // 返回地址数据
    saveAddress (pointid, event) {
      this.$emit('saveDetailAddress', JSON.stringify(this.poiArr[pointid]), this.otherAddress)
      this.closeMap()
    },
    // 关键词搜索
    searchKeyword () {
      this.hide = true
      this.poiArr = []
      this.placeSearchComponent.search(this.inputSearchVal, (status, res) => {
        // 查询成功时，result即对应匹配的POI信息
        if (status !== 'no_data' && status !== 'error') {
          let poiArr = res.poiList.pois
          this.resultCount = res.poiList.count
          this.poiArr = poiArr // 左边要渲染的数据
        }
      })
    },
    // 初始化搜索工具
    mapSearchInit () {
      let that = this
      // 绑定自动提示
      AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], function () {
        var autoOptions = {
          input: 'search',
          city: that.cityCode
        }
        var autoCompleteComponent = new AMap.Autocomplete(autoOptions)
        // 注册监听Autocomplete选中项
        AMap.event.addListener(autoCompleteComponent, 'select', function (data) {
        })
        that.autoCompleteComponent = autoCompleteComponent
        // 注册placeSearch组件
        that.placeSearchComponent = new AMap.PlaceSearch({
          // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
          city: that.cityCode
        })
      })
      if (this.showCity) {
        // 初始化省市区
        that.initCity()
      }
    },
    // 对地图的位置 标点
    marker (location) {
      this.map.clearMap()
      var marker = new AMap.Marker({
        position: location
      })
      // 将创建的点标记添加到已有的地图实例：
      this.map.add(marker)
    },
    //  初始化 天气和省市区
    initCity () {
      this.addressComponent = []
      var opts = {
        subdistrict: 1,   // 返回下一级行政区
        showbiz: false    // 最后一级返回街道信息
      }
      // 获取当前位置
      AMap.plugin('AMap.Geolocation', () => {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位，默认：true
          convert: true,
          showMarker: true,
          panToLocation: true,
          timeout: 10000
        })

        geolocation.getCurrentPosition((status, res) => {
          // 获取省市区
          // let province = res.addressComponent.province
          // let city = res.addressComponent.city
          // let district = res.addressComponent.district
          this.addressComponentObj = res.addressComponent
          if (status === 'complete') {
            // this.cityCode = res.addressComponent.adcode
            // 加载天气组组件
            // that.weatherFun(that.centerCity)
          }
        })
      })
      this.district = new AMap.DistrictSearch(opts)// 注意：需要使用插件同步下发功能才能这样直接使用
      this.district.search('中国', (status, result) => {
        if (status === 'complete') {
          this.provinceList = result.districtList[0].districtList
        }
      })
    },
    provinceChange (val, level) {
      // 清空下一级别的下拉列表
      if (level === 'province') {
        this.province = val.name
        this.city = ''
        this.district = ''
        this.area = ''
      } else if (level === 'city') {
        this.city = val.name
        this.district = ''
        this.area = ''
      } else if (level === 'district') {
        this.districtVal = val.name
        this.area = ''
      }
      this.cityCode = val.adcode
      this.mapSearchInit()
      this.map.setCenter(val.center)
      let district = new AMap.DistrictSearch()
      district.search(val.adcode, (status, result) => {
        if (status === 'complete') {
          if (level === 'province') {
            this.cityList = result.districtList[0].districtList
          }
          if (level === 'city') {
            this.districtList = result.districtList[0].districtList
          }
        }
      })
    },
    // 经纬度转化为详细地址
    getAddress (lng, lat) {
      let that = this
      AMap.plugin('AMap.Geocoder', function () {
        let geocoder = new AMap.Geocoder({
          radius: 100,
          extensions: 'all'
        })
        geocoder.getAddress([lng, lat], function (status, result) {
        	let res=result.regeocode,addressInfo=res.addressComponent;
        	console.log(241,res)
          if (status === 'complete' && result.info === 'OK') {
            let province = addressInfo.province
            let city = addressInfo.city
            let district = addressInfo.district
            let addressComponent = city?[province, city, district]:[province, district]
            console.log(addressComponent)
            let districtCode=Number(addressInfo.adcode),
            cityCode=Math.floor(districtCode/100)*100,
            provinceCode=Math.floor(districtCode/10000)*10000;
            let item = {
            	codes:{
            		province:provinceCode,
            		city:cityCode,
            		district:districtCode
            	},
              location: {
                lat: lat, lng: lng
              },
              address: res.formattedAddress,
              addressComponent: addressComponent.join(';')
            }
            that.$emit('saveDetailAddress', JSON.stringify(item))
            that.closeMap()
          }
        })
      })
    },
    // 关闭地图弹窗
    closeMap () {
      this.resultCount = 0
      this.mapVisible = false
      this.inputSearchVal = ''
      this.poiArr = []
    },
    //  初始化地图map

    initMap (cityCode = '') {
      let that = this
      const loading = that.$loading({
        lock: true,
        text: '数据拉取中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.6)'
      })
      this.cityCode = cityCode
      // 地图实例
      that.map = new AMap.Map('container', {
        resizeEnable: true, // 允许缩放
        // eslint-disable-next-line no-irregular-whitespace
        zoom: 15 　　　　　　 // 设置地图的缩放级别，0 - 20
      })
      // 为地图注册click事件获取鼠标点击出的经纬度坐标
      that.map.on('click', function (e) {
        let lng = e.lnglat.lng
        let lat = e.lnglat.lat
        that.getAddress(lng, lat)
      })
      if (cityCode) {
        AMap.plugin('AMap.Geocoder', function () {
          var geocoder = new AMap.Geocoder()
          geocoder.getLocation(cityCode, function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // 经纬度
              var lng = result.geocodes[0].location.lng
              var lat = result.geocodes[0].location.lat
              that.map.setCenter([lng, lat])
              that.cityCode = result.geocodes[0].addressComponent.city
              that.mapSearchInit()
            } else {
              console.log('定位失败！')
            }
          })
        })
      }
      if (this.showCity) {
        that.$refs.searchCity.initCity()
      }
      // 如果有默认的经纬度 地图定位到对应的位置
      if (this.initVal) {
        let positon = this.initVal.split(',')
        this.map.setZoomAndCenter(15, positon)
        // 选择后对地图标点
        this.marker(positon)
      }
      setTimeout(() => {
        loading.close()
      }, 500)
    }
    //  打开地图
    // openMap () {
    //   this.$refs.gmap.mapVisible = true
    //   this.$nextTick(() => {
    //     this.$refs.gmap.initMap()
    //   })
    // }
    /* ================  地图相关 结束 ==================   */
  }
}
</script>

<style scoped lang="less">

::v-deep.cPadding {
  .el-card__body {
    padding: 13px 11px !important;
  }

  .f_end {
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}

.showAddress {
  width: 100%;
  height: 100%;

  ::v-deep.el-dialog {
    width: 100% !important;
    height: 100%;

    .el-dialog__body {
      width: 100%;
      height: 100%;
      padding: 0px !important;

    }
  }

  .dialogSearch {
    position: fixed;
    top: 40px;
    left: 0;
    width: 100%;
    height: 45px;
    background: #fff;
    padding: 0 20px;
    display: flex;
    z-index: 999;

    ::v-deep .el-input {
      //width: 300px;

      .el-input__inner {
        width: inherit;
      }
    }
  }

  .searchBox {
    width: 300px;
    background: #fff;
    position: absolute;
    top: 85px;
    left: 181px;
    overflow-y: scroll;
    border: 1px solid #AAAAAA;
    height: calc(100% - 105px);
    padding: 9px;
    box-sizing: border-box;
    z-index: 999;

    .s_p1 {
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #333333;
      text-indent: 2em;
      margin: 20px 0;
    }

    .s_item:hover {
      background: #dfdfdf;
    }

    .s_item {
      display: flex;
      align-items: flex-start;
      line-height: 20px;
      margin-top: 10px;
      width: 100%;
      padding: 10px 20px;

      .icon {
        height: 15px;
        width: 15px;
        display: inline-block;
        background: url("~@/assets/img/location.png") center no-repeat;
        margin-right: 10px;
        margin-top: 3px;
      }

      .s_p2 {
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #333333;
      }

      .s_p3 {
        font-size: 12px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #333333;
        opacity: 0.6;
        margin-top: 10px;
      }
    }

  }

  //.searchBox {
  //  position: fixed;
  //  top: 85px;
  //  right: 0;
  //  background: #fff;
  //  width: 310px;
  //  height: calc(100% - 85px);
  //  padding: 9px;
  //  box-sizing: border-box;
  //  z-index: 999;
  //
  //  p {
  //    margin-bottom: 10px;
  //  }
  //
  //  .box-card {
  //    margin-bottom: 10px;
  //  }
  //}


  .amap_lib_placeSearch {
    height: 100%;
    overflow-y: scroll;
    background: #fff;

    .poibox {
      border-bottom: 1px solid #eaeaea;
      cursor: pointer;
      padding: 5px 0 5px 10px;
      position: relative;
      min-height: 35px;

      .selected {
        background-image: url(https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png) !important;
      }

      &:hover {
        background: #f6f6f6;
      }

      .poi-img {
        float: right;
        margin: 3px 8px 0;
        width: 90px;
        height: 56px;
        overflow: hidden;
      }

      .poi-title {
        margin-left: 25px;
        font-size: 13px;
        overflow: hidden;
      }

      .poi-info {
        word-break: break-all;
        margin: 0 0 0 25px;
        overflow: hidden;

        p {
          color: #999;
          font-family: Tahoma;
          line-height: 20px;
          font-size: 12px;
        }
      }

      .poibox-icon {
        margin-left: 7px;
        margin-top: 4px;
      }

      .amap_lib_placeSearch_poi {
        background: url(https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png) no-repeat;
        height: 31px;
        width: 19px;
        cursor: pointer;
        left: -1px;
        text-align: center;
        color: #fff;
        font: 12px arial, simsun, sans-serif;
        padding-top: 3px;
        position: absolute;
      }
    }
  }

  .btn {
    position: fixed;
    bottom: 20px;
    left: 50%;
    padding: 10px;
  }


  .s_ads {
    position: fixed;
    top: 50px;
    right: 10px;
    height: 83%;
  }
}

::v-deep.dialogSearchMap {
  display: flex;
  align-items: center;

  .input-item {
    display: flex;
    align-items: center;

    .p_1 {
      margin: 0 10px;
    }
  }

  .el-input {
    display: flex;
    align-items: center;
    margin-bottom: 0 !important;

    .el-input__inner {
      width: 260px !important;
      -webkit-appearance: none;
      background-color: #FFF;
      background-image: none;
      border-radius: 4px;
      border: 1px solid #DCDFE6 !important;
      box-sizing: border-box;
      color: #606266 !important;
      display: inline-block;
      font-size: inherit;
      line-height: 40px;
      outline: 0;
      padding: 0 15px;
    }
  }

  .el-select {
    .el-input__inner {
      width: 98px !important;
    }
  }

}

</style>
